<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 该页面已完成
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-input
          clearable
          v-model="query.creatorName"
          placeholder="用户名"
          class="handle-input mr10"
        ></el-input>
        <el-select
          clearable
          v-model="query.status"
          placeholder="状态"
          class="handle-select mr10"
        >
          <el-option key="1" label="失败" value="0"></el-option>
          <el-option key="2" label="成功" value="1"></el-option>
          <el-option key="3" label="账号已绑定" value="2"></el-option>
        </el-select>

        <el-button type="danger" @click="handleSearch">查询</el-button>

        <el-button
          type="primary"
          @click="handleExport"
          v-if="sllPermissions.includes('sys:loglogin:export')"
          >导出</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
        @sort-change="sortChange"
      >
        <el-table-column
          prop="creatorName"
          label="用户名"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="operation"
          label="操作类型"
          align="center"
        ></el-table-column>

        <el-table-column sortable label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-tag
              :type="
                scope.row.status === '成功'
                  ? 'success'
                  : scope.row.status === '失败'
                  ? 'danger'
                  : ''
              "
              >{{ scope.row.status }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="ip"
          label="操作IP"
          align="center"
        ></el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          prop="userAgent"
          label="User-Agent"
          align="center"
        ></el-table-column>
        <el-table-column
          sortable
          prop="createDate"
          label="创建时间"
          align="center"
        ></el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total,sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20, 30]"
          @size-change="handleSizeChange"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
// import { sysLogLoginMixin } from "../../common/js/logManage";
// console.log(sysLogLoginMixin);
import { mapGetters } from "vuex";
export default {
  name: "sysloglogin",
  // mixins: [sysLogLoginMixin],

  data() {
    return {
      sllPermissions: [],
      query: {
        order: "",
        orderField: "",
        pageIndex: 1,
        pageSize: 20,
        creatorName: "",
        status: ""
      },
      tableData: [
        {
          id: "",
          operation: "",
          status: "成功",
          userAgent: "",
          ip: "",
          creatorName: "",
          createDate: ""
        }
      ],
      multipleSelection: [],
      delList: [],
      pageTotal: 0,
      idx: -1
    };
  },
  methods: {
    // 获取数据
    getSysLLData({
      order = this.query.order,
      orderField = this.query.orderField,
      page = this.query.pageIndex,
      limit = this.query.pageSize,
      creatorName = this.query.creatorName,
      status = this.query.status,
      _t = Date.now()
    }) {
      this.$axios
        .get("/sys/log/login/page", {
          params: {
            order,
            orderField,
            page,
            limit,
            creatorName,
            status,
            _t
          }
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          // console.log(res);
          this.pageTotal = res.data.total || 0;
          this.tableData = res.data.list;
          this.tableData.map(item => {
            item.operation = item.operation === 0 ? "登录" : "退出";
            item.status = item.status === 1 ? "成功" : "失败";
          });
        })
        .catch(() => {});
    },

    // 表头排序
    sortChange({ column, prop, order }) {
      // console.log(column, prop, order);
      prop = prop === "createDate" ? "create_date" : prop;
      this.$set(this.query, "orderField", prop);
      if (order === "ascending") {
        this.$set(this.query, "order", order.substr(0, 3));
        this.getSysLLData({});
      } else if (order === "descending") {
        this.$set(this.query, "order", order.substr(0, 4));
        this.getSysLLData({});
      }
    },
    getToken(token) {
      var arr = token.split(";");
      for (var i = 0; i < arr.length; i++) {
        if (arr[i].split("=")[0].trim() === "token") {
          return arr[i].split("=")[1];
        }
      }
    },
    // 导出excel
    handleExport() {
      this.$axios
        .get("/sys/log/login/export", {
          params: {
            token: this.getToken(document.cookie),
            creatorName: this.query.creatorName,
            status: this.query.status
          },
          responseType: "blob"
        })
        .then(res => {
          // 导出excel表格
          // console.log(res);
          const link = document.createElement("a");
          let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          let num = "";
          for (let i = 0; i < 10; i++) {
            num += Math.ceil(Math.random() * 10);
          }
          link.setAttribute("download", "用户_" + num + ".xls");
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch(error => {
          this.$Notice.error({ title: "错误", desc: "网络连接错误" });
          // console.log(error);
        });
    },
    // 触发搜索按钮
    handleSearch() {
      this.$set(this.query, "pageIndex", 1);
      this.getSysLLData({
        creatorName: this.query.creatorName,
        status: this.query.status
      });
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, "pageIndex", val);
      this.getSysLLData({});
    },
    handleSizeChange(val) {
      this.$set(this.query, "pageSize", val);
      this.getSysLLData();
    }
  },
  created() {
    this.getSysLLData({});
    this.sllPermissions = this.permissions;
  },
  computed: {
    ...mapGetters(["permissions"])
  },
  watch: {
    "$route.path": function(newVal, oldVal) {
      if (newVal == "/sys-log-login") {
        this.sllPermissions = this.permissions;
      }
    },
    // 刷新浏览器时触发
    permissions: function(newVal, oldVal) {
      // console.log(newVal, oldVal);
      this.sllPermissions = newVal;
    }
  }
};
</script>

<style scoped>
@import url("../../common/css/index.css");
</style>
